# -*- coding: utf-8 -*-
import json
# HTTP
from django.utils import simplejson
from django.shortcuts import render_to_response
from argus.forms import *
from argus.views import getDefaultRecentAlarms,getPrefixRange,geo
from django.template import RequestContext
from django.core.context_processors import csrf
from django.contrib.auth.decorators import login_required

#from django.db.models import Q
from django.db import connection
from defence.models import *
from argus.hijacking.models import *
from django.db.models import Count

import time, string

def getHijackings(topx, prefixs=[], ASNs=[]):
  cursor = connection.cursor()
  sql_param = []
  prefix_condition = ""
  AS_condition = ""
  if prefixs:
    #(ipbeg, ipend, psize) = getPrefixRange(prefix)
    if len(prefixs) == 1:
      prefix_condition = " prefix_dec = %s " % prefixs[0]
    else:
      prefix_condition = " prefix_dec in %s " % str(tuple(prefixs))
    #sql_param.append(prefixs)
  if ASNs:
    if len(ASNs) == 1:
      AS_condition = """ (homeas = %s OR oldhomeas = %s
        OR as0 = %s OR as1 = %s OR as2 = %s) """ % (ASNs[0],ASNs[0],ASNs[0],ASNs[0],ASNs[0])
    else:
      sql = str(tuple(ASNs))
      AS_condition = """ (homeas in %s OR oldhomeas in %s
        OR as0 in %s OR as1 in %s OR as2 in %s) """ % (sql,sql,sql,sql,sql)
  sql_param.append(topx)
  
  condition = ""
  if prefixs:
    if ASNs:
      condition = " AND (" + prefix_condition + " OR " + AS_condition + " )"
    else:
      condition = " AND " + prefix_condition
  else:
    if ASNs:
      condition = " AND " + AS_condition
  if not condition:
    return []
  cursor.execute(""" SELECT alarm_id FROM hijacking WHERE is_hijacking = 'Y' """
    + condition + """ ORDER BY alarm_id DESC LIMIT %s """, sql_param)
  alarms = cursor.fetchall()
  alarms_info = {}
  alarm_ids = []
  for am in alarms:
    # FirstAlarm, AlarmLast, E(Fing. in [low, high]), OldOrigins, FirstBadRoute
    alarm_ids.append(am[0])
  alarms = Alarm.objects.filter(alarm_id__in = alarm_ids).order_by('-alarm_id')

  alarms_detail = []
  for i in xrange(len(alarms)):
    prefix_cc = geo.country_code_by_addr(
      alarms[i].prefix_dec[:alarms[i].prefix_dec.index('/')])
    if not prefix_cc:
      prefix_cc = ""
    as0 = as1 = as2 = 0
    if alarms[i].bad_path:
      ASes = string.split(alarms[i].bad_path, ' ')
      as2 = ASes[-1]
      as1 = ASes[-2]
      if len(ASes) == 3: as0 = int(ASes[0])
    num_prefix = Alarm.objects.filter(
        time = alarms[i].time, homeas = alarms[i].homeas,
        bad_path = alarms[i].bad_path).count() - 1
    alarms_detail.append((
      alarms[i],
      time.strftime("%y-%m-%d %T", time.gmtime(alarms[i].time)),
      as0, as1, as2, num_prefix, prefix_cc,
    ))
  return alarms_detail

@login_required
def myAlarm(request, asn=''):
  # recent alarms
  template_var = {}
  user = request.user
  alarms_detail = []
  allPrefixs = user.prefix_set.all()
  allASNs = user.asn_set.all()
  prefixs = []
  for prefix in allPrefixs:
    prefixs.append(prefix.dec.encode("utf-8"))
  ASNs = []
  for ASN in allASNs:
    ASNs.append(int(ASN.number))
  alarms_detail.extend(getHijackings(50, prefixs, ASNs))
  template_var["alarms"] = alarms_detail
  form = AlarmFilterForm(
      initial = {'topx': 10, 'fig_low': 0.6, 'fig_high': 1.0, 'fig_last': 10,
            'prefix': '', 'AS': ''} )
  template_var["form"] = form
  return render_to_response('defence/myAlarm.html',template_var,context_instance=RequestContext(request))

@login_required
def myPrefix(request):
  template_var = {}
  user = request.user
  if request.method == 'POST':
    prefix = request.POST.get('prefix',None)
    deletePrefixId = request.POST.get('deletePrefixId',None)
    if deletePrefixId is not None:
      template_var["msg"] = "fails to delete an prefix"
      try:
        prefixObj = Prefix.objects.get(id=int(deletePrefixId))
        if prefixObj.user == user:
          prefixObj.delete()
          template_var["msg"] = "successfully delete an prefix"
      except:
        pass
    else:
      if prefix is None or prefix == "":
        template_var["error"] = "empty"
      else:
        iprg = prefix2range(prefix)
        if iprg == "-1":
          template_var["error"] = "IPv4: A.B.C.D/M (0&le;M&le;32), IPv6: A:B:C::/M (0&le;M&le;128)"
        else:
          (ipaddr, length) = prefix.split('/')
          if Prefix.objects.filter(user=user,dec=prefix):
            template_var["msg"] = "prefix already exists"
          elif Prefix.objects.create(user=user,dec=prefix,ipaddr=ipaddr,length=length):
            template_var["msg"] = "successfully add an prefix"
          else:
            template_var["msg"] = "fails to add an prefix"
  Prefixs = Prefix.objects.filter(user=user)
  template_var["Prefixs"] = Prefixs
  return render_to_response('defence/myPrefix.html',template_var,context_instance=RequestContext(request))

@login_required
def myASN(request):
  template_var = {}
  user = request.user
  if request.method == 'POST':
    asn = request.POST.get('asn',None)
    deleteASN = request.POST.get('deleteASN',None)
    if deleteASN is not None:
      try:
        asnObj = ASN.objects.get(user=user,number=int(deleteASN))
        asnObj.delete()
        template_var["msg"] = "successfully delete an asn"
      except:
        template_var["msg"] = "fails to delete an asn"
    else:
      if asn is None or asn == "":
        template_var["error"] = "empty"
      elif int(asn) < 1 or int(asn) > 4294967295:
        template_var["error"] = "int: [1, 2^32]"
      elif ASN.objects.filter(user=user,number=asn):
        template_var["msg"] = "asn already exists"
      elif ASN.objects.create(user=user,number=asn):
        template_var["msg"] = "successfully add an asn"
      else:
        template_var["msg"] = "fails to add an asn"
  ASNs = ASN.objects.filter(user=user)
  template_var["ASNs"] = ASNs
  return render_to_response('defence/myASN.html',template_var,context_instance=RequestContext(request))









